<template>
  <div class="daily-report-container">
    <div class="page-header">
      <div class="header-left">
        <h2>日报管理</h2>
      </div>
      <div class="header-actions">
        <el-date-picker
          v-model="selectedDate"
          type="date"
          placeholder="选择日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          :disabled-date="disableFutureDates"
          @change="loadDailyReport"
        />
        <el-button type="primary" @click="refreshReport" :loading="loading">
          <el-icon><Refresh /></el-icon>
          刷新数据
        </el-button>
        <el-button type="success" @click="exportReport" :loading="exporting">
          <el-icon><Download /></el-icon>
          导出报表
        </el-button>
        <el-button type="warning" @click="exportEnhancedReport" :loading="exportingEnhanced">
          <el-icon><Download /></el-icon>
          导出美化报表
        </el-button>
      </div>
    </div>
    
    <!-- 销售概览 -->
    <el-card class="overview-card">
      <template #header>
        <div class="card-header">
          <span>销售概览</span>
          <el-tag type="success">{{ selectedDate }}</el-tag>
        </div>
      </template>
      
      <div class="overview-statistics">
        <div class="statistic-card">
          <div class="statistic-value">{{ reportData.orderCount || 0 }}</div>
          <div class="statistic-label">订单数</div>
        </div>
        <div class="statistic-card highlight">
          <div class="statistic-value">¥{{ formatNumber(reportData.totalSales || 0) }}</div>
          <div class="statistic-label">营业额</div>
        </div>
        <div class="statistic-card">
          <div class="statistic-value">¥{{ formatNumber(reportData.averageOrder || 0) }}</div>
          <div class="statistic-label">客单价</div>
        </div>
      </div>
    </el-card>
    
    <!-- 图表区域 -->
    <div class="charts-container">
      <!-- 支付方式分布 -->
      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>支付方式分布</span>
          </div>
        </template>
        <div class="chart-wrapper" id="payment-chart"></div>
      </el-card>
      
      <!-- 渠道销售分布 -->
      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>渠道销售分布</span>
          </div>
        </template>
        <div class="chart-wrapper" id="channel-chart"></div>
      </el-card>
    </div>
    
    <!-- 时段销售趋势 -->
    <el-card class="trend-card">
      <template #header>
        <div class="card-header">
          <span>时段销售趋势</span>
        </div>
      </template>
      <div class="chart-wrapper" id="hourly-trend-chart"></div>
    </el-card>
    
    <!-- 热销商品排行 -->
    <el-card class="products-card">
      <template #header>
        <div class="card-header">
          <span>热销商品排行</span>
        </div>
      </template>
      
      <el-table :data="reportData.topProducts || []" stripe style="width: 100%">
        <el-table-column type="index" label="排名" width="80" />
        <el-table-column prop="name" label="商品名称" />
        <el-table-column prop="quantity" label="销售数量" width="120" />
        <el-table-column prop="amount" label="销售金额" width="150">
          <template #default="scope">
            ¥{{ formatNumber(scope.row.amount) }}
          </template>
        </el-table-column>
        <el-table-column prop="percentage" label="占比" width="120">
          <template #default="scope">
            {{ (scope.row.percentage * 100).toFixed(2) }}%
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 历史日报列表 -->
    <el-card class="history-card">
      <template #header>
        <div class="card-header">
          <span>历史日报记录 (测试修改)</span>
          <el-input
            v-model="searchText"
            placeholder="搜索日报记录"
            prefix-icon="Search"
            clearable
            style="width: 250px"
          />
        </div>
      </template>
      
      <el-table 
        :data="filteredHistoryReports" 
        stripe 
        border
        highlight-current-row
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 'bold' }"
        :row-class-name="tableRowClassName"
      >
        <el-table-column prop="date" label="日期" width="120" align="center" />
        <el-table-column prop="orderCount" label="订单数" width="100" align="center" />
        <el-table-column prop="totalSales" label="营业额" width="150" align="center">
          <template #default="scope">
            <span class="sales-amount">¥{{ formatNumber(scope.row.totalSales) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="averageOrder" label="客单价" width="150" align="center">
          <template #default="scope">
            <span class="average-amount">¥{{ formatNumber(scope.row.averageOrder) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="200" align="center">
          <template #default="scope">
            <div class="action-buttons">
              <el-button 
                type="primary" 
                size="small" 
                @click="viewReportDetails(scope.row.date)"
                :icon="View"
              >
                查看数据
              </el-button>
              <el-button 
                type="success" 
                size="small" 
                @click="exportSpecificEnhancedReport(scope.row.date)"
                :icon="Download"
              >
                导出
              </el-button>
              <el-button 
                type="info" 
                size="small" 
                @click="viewOrdersByDate(scope.row.date)"
                :icon="List"
              >
                数据详情
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="historyReports.length"
          background
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, Download, Search, View, PictureRounded, List } from '@element-plus/icons-vue'
import api from '@/utils/api'
import reportsApi from '@/api/reports'
import * as echarts from 'echarts/core'
import { PieChart, BarChart, LineChart } from 'echarts/charts'
import { 
  TitleComponent, 
  TooltipComponent, 
  LegendComponent, 
  GridComponent 
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import { useRouter } from 'vue-router'

// 注册必要的组件
echarts.use([
  TitleComponent, 
  TooltipComponent, 
  LegendComponent, 
  GridComponent,
  PieChart,
  BarChart,
  LineChart,
  CanvasRenderer
])

// 日期选择
const selectedDate = ref(new Date().toISOString().split('T')[0]) // 默认今天
const disableFutureDates = (date) => {
  return date > new Date()
}



// 获取路由实例
const router = useRouter()

// 报表数据
const reportData = ref({
  orderCount: 0,
  totalSales: 0,
  averageOrder: 0,
  paymentMethods: {},
  channelSales: [],
  hourlyTrends: [],
  topProducts: []
})

// 历史报表
const historyReports = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const searchText = ref('')

// 加载状态
const loading = ref(false)
const exporting = ref(false)
const exportingEnhanced = ref(false)

// 图表实例
let paymentChart = null
let channelChart = null
let hourlyTrendChart = null

// 过滤后的历史报表
const filteredHistoryReports = computed(() => {
  if (!searchText.value) {
    return historyReports.value.slice(
      (currentPage.value - 1) * pageSize.value,
      currentPage.value * pageSize.value
    )
  }
  
  const filtered = historyReports.value.filter(report => {
    return report.date.includes(searchText.value)
  })
  
  return filtered.slice(
    (currentPage.value - 1) * pageSize.value,
    currentPage.value * pageSize.value
  )
})

// 加载日报数据
const loadDailyReport = async () => {
  if (!selectedDate.value) return
  
  try {
    loading.value = true
    
    // 调用API获取日报数据
    const response = await api.get(`/reports/daily/${selectedDate.value}`)
    
    if (response.data && response.data.status === 'success') {
      reportData.value = response.data.data
      
      // 渲染图表
      renderCharts()
    } else {
      ElMessage.warning('获取日报数据失败，请稍后重试')
    }
  } catch (error) {
    console.error('获取日报数据失败:', error)
    ElMessage.error('获取日报数据失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 加载历史日报列表
const loadHistoryReports = async () => {
  try {
    const response = await api.get('/reports/daily/history')
    
    if (response.data && response.data.status === 'success') {
      historyReports.value = response.data.data
    }
  } catch (error) {
    console.error('获取历史日报失败:', error)
  }
}

// 刷新报表数据
const refreshReport = () => {
  loadDailyReport()
}

// 导出报表
const exportReport = async () => {
  try {
    exporting.value = true
    
    const response = await api.get(`/reports/daily/${selectedDate.value}/export`, {
      responseType: 'blob'
    })
    
    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([response.data]))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', `日报-${selectedDate.value}.xlsx`)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    ElMessage.success('报表导出成功')
  } catch (error) {
    console.error('导出报表失败:', error)
    ElMessage.error('导出报表失败')
  } finally {
    exporting.value = false
  }
}

// 导出美化版日报
const exportEnhancedReport = async () => {
  try {
    exportingEnhanced.value = true
    await reportsApi.exportEnhancedDailyReport(selectedDate.value)
    ElMessage.success('美化版报表导出成功')
  } catch (error) {
    console.error('导出美化版报表失败:', error)
    ElMessage.error('导出美化版报表失败')
  } finally {
    exportingEnhanced.value = false
  }
}

// 导出特定日期的报表
const exportSpecificReport = (date) => {
  selectedDate.value = date
  exportReport()
}

// 导出特定日期的美化版报表
const exportSpecificEnhancedReport = (date) => {
  selectedDate.value = date
  exportEnhancedReport()
}

// 查看特定日期的报表详情
const viewReportDetails = (date) => {
  selectedDate.value = date
  loadDailyReport()
  // 滚动到顶部
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

// 查看特定日期的订单详情
const viewOrdersByDate = (date) => {
  selectedDate.value = date
  ElMessageBox.confirm(
    `确定要查看 ${selectedDate.value} 的订单详情吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info',
    }
  ).then(() => {
    ElMessage.success(`已跳转到 ${selectedDate.value} 的订单管理页面`)
    // 使用Vue Router导航到订单管理页面
    router.push({
      path: '/orders',
      query: { date: selectedDate.value }
    })
  }).catch(() => {
    // 用户取消操作
  })
}



// 渲染图表
const renderCharts = () => {
  // 支付方式分布图表
  renderPaymentChart()
  
  // 渠道销售分布图表
  renderChannelChart()
  
  // 时段销售趋势图表
  renderHourlyTrendChart()
}

// 渲染支付方式分布图表
const renderPaymentChart = () => {
  if (!reportData.value.paymentMethods) return
  
  const paymentMethodsData = []
  for (const [method, amount] of Object.entries(reportData.value.paymentMethods)) {
    paymentMethodsData.push({
      name: getPaymentMethodName(method),
      value: amount
    })
  }
  
  if (!paymentChart) {
    paymentChart = echarts.init(document.getElementById('payment-chart'))
  }
  
  const option = {
    title: {
      text: '支付方式分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: ¥{c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 10,
      data: paymentMethodsData.map(item => item.name)
    },
    series: [
      {
        name: '支付金额',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: paymentMethodsData
      }
    ]
  }
  
  paymentChart.setOption(option)
}

// 渲染渠道销售分布图表
const renderChannelChart = () => {
  if (!reportData.value.channelSales) return
  
  const channelData = reportData.value.channelSales.map(item => ({
    name: item.name,
    value: item.amount
  }))
  
  if (!channelChart) {
    channelChart = echarts.init(document.getElementById('channel-chart'))
  }
  
  const option = {
    title: {
      text: '渠道销售分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: ¥{c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 10,
      data: channelData.map(item => item.name)
    },
    series: [
      {
        name: '销售金额',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: channelData
      }
    ]
  }
  
  channelChart.setOption(option)
}

// 渲染时段销售趋势图表
const renderHourlyTrendChart = () => {
  if (!reportData.value.hourlyTrends) return
  
  const hours = reportData.value.hourlyTrends.map(item => item.hour)
  const sales = reportData.value.hourlyTrends.map(item => item.amount)
  const orders = reportData.value.hourlyTrends.map(item => item.orderCount)
  
  if (!hourlyTrendChart) {
    hourlyTrendChart = echarts.init(document.getElementById('hourly-trend-chart'))
  }
  
  const option = {
    title: {
      text: '时段销售趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['销售额', '订单数'],
      bottom: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: hours,
      axisLabel: {
        formatter: '{value}:00'
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '销售额',
        axisLabel: {
          formatter: '¥{value}'
        }
      },
      {
        type: 'value',
        name: '订单数',
        axisLabel: {
          formatter: '{value}'
        }
      }
    ],
    series: [
      {
        name: '销售额',
        type: 'bar',
        data: sales
      },
      {
        name: '订单数',
        type: 'line',
        yAxisIndex: 1,
        data: orders
      }
    ]
  }
  
  hourlyTrendChart.setOption(option)
}

// 格式化数字
const formatNumber = (num) => {
  if (num === undefined || num === null) return '0.00'
  return num.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

// 获取支付方式名称
const getPaymentMethodName = (method) => {
  const methodMap = {
    'cash': '现金',
    'wechat': '微信支付',
    'alipay': '支付宝',
    'complimentary': '招待',
    'mixed': '混合支付'
  }
  return methodMap[method] || method
}

// 表格行样式
const tableRowClassName = ({ rowIndex }) => {
  return rowIndex % 2 === 0 ? 'even-row' : 'odd-row'
}

// 监听窗口大小变化，重新调整图表大小
const handleResize = () => {
  if (paymentChart) paymentChart.resize()
  if (channelChart) channelChart.resize()
  if (hourlyTrendChart) hourlyTrendChart.resize()
}

// 监听日期变化
watch(selectedDate, () => {
  loadDailyReport()
})

// 组件挂载时获取数据
onMounted(() => {

  
  // 加载当天的日报数据
  loadDailyReport()
  
  // 加载历史日报列表
  loadHistoryReports()
  
  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize)
})

// 组件卸载时清理
onUnmounted(() => {
  // 销毁图表实例
  if (paymentChart) paymentChart.dispose()
  if (channelChart) channelChart.dispose()
  if (hourlyTrendChart) hourlyTrendChart.dispose()

  // 移除窗口大小变化监听
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.daily-report-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

.overview-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.overview-statistics {
  display: flex;
  justify-content: space-between;
  margin: 20px 0;
}

.statistic-card {
  flex: 1;
  text-align: center;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 6px;
  margin: 0 10px;
}

.statistic-card:first-child {
  margin-left: 0;
}

.statistic-card:last-child {
  margin-right: 0;
}

.statistic-card.highlight {
  background-color: #ecf5ff;
  border: 1px solid #d9ecff;
}

.statistic-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
}

.highlight .statistic-value {
  color: #409EFF;
}

.statistic-label {
  font-size: 14px;
  color: #606266;
}

.charts-container {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.chart-card {
  flex: 1;
}

.chart-wrapper {
  height: 300px;
}

.trend-card {
  margin-bottom: 20px;
}

.products-card {
  margin-bottom: 20px;
}

.history-card {
  margin-top: 30px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.history-card :deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

.history-card :deep(.el-table th) {
  background-color: #f5f7fa !important;
  font-weight: bold;
  color: #606266;
  padding: 12px 0;
}

.history-card :deep(.el-table td) {
  padding: 12px 0;
}

.history-card :deep(.el-table .even-row) {
  background-color: #fafafa;
}

.history-card :deep(.el-table .odd-row) {
  background-color: #ffffff;
}

.history-card :deep(.el-table .el-table__row:hover) {
  background-color: #ecf5ff !important;
}

.history-card .action-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
}

.sales-amount {
  color: #67c23a;
  font-weight: bold;
}

.average-amount {
  color: #409EFF;
  font-weight: bold;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}



@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .header-actions {
    margin-top: 10px;
    width: 100%;
    flex-wrap: wrap;
  }
  
  .charts-container {
    flex-direction: column;
  }
}
</style> 